package com.demo.weixin.conf;

import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.apache.http.client.HttpClient;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class RestTemplateConfig {

    @Resource
    private HttpClient httpClient;
    @Resource
    private FastJsonConfig fastJsonConfig;
    @Resource
    private RestTemplateBuilder restTemplateBuilder;


    @Bean
    public ClientHttpRequestFactory clientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        clientHttpRequestFactory.setHttpClient(httpClient);
        clientHttpRequestFactory.setConnectTimeout(2000);
        clientHttpRequestFactory.setReadTimeout(3000);
        clientHttpRequestFactory.setConnectionRequestTimeout(2000);
        return clientHttpRequestFactory;
    }

    @Bean
    @Primary
    public RestTemplate restTemplate()  throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        RestTemplate restTemplate = new RestTemplate();

        restTemplate.setRequestFactory(clientHttpRequestFactory());

        List<HttpMessageConverter<?>> converters =  restTemplate.getMessageConverters();

        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(new ArrayList<MediaType>() {
            private static final long serialVersionUID = 6688659690562975474L;
            {
                this.add(MediaType.APPLICATION_JSON);
                this.add(MediaType.APPLICATION_JSON_UTF8);
            }});
        converters.add(fastJsonHttpMessageConverter);
        converters.set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));

        return restTemplate;
    }
}
